<?php
namespace Home\Model;
use Think\Model;
/**
 * 权限规则model
 */
class MateModel extends Model{

	/**
	 * 初始化
	 */
	public function __construct(){

	}

	/**
	 * 首页
	 */
	public function index(){

		$id = I("get.id",'','int');

		if(!empty($id)){

			//获取用户UID
			$map['a.id'] = array("eq",$id);

			$user_info = M("addpage_info")->alias("a")->field("a.user_id,a.typeid,b.qq")->join("LEFT JOIN __USERS__ b ON a.user_id = b.id")->where($map)->find();

			if($user_info['typeid'] == 1){

				//获取上传首图
				$where['b.typeid'] = array("eq",0);
				$where['b.addpage_info_id'] = array("eq",$id);
				$where['b.user_id'] = array("eq",$user_info['user_id']);
				$index_images = M("addpage_details_images")->alias("a")->field("a.image")->join("LEFT JOIN __ADDPAGE_DETAILS_IMAGES_SERIAL__ b ON a.images_serial_id = b.id")->where($where)->order("a.id asc")->select();

				//获取按钮设置
				$details_index = M("addpage_details_index")->where("addpage_info_id=".$id)->find();

				//获取图文设置
				$where = array();
				$where['typeid'] = array("in",array(1,2));
				$where['addpage_info_id'] = array("eq",$id);
				$where['user_id'] = array("eq",$user_info['user_id']);
				$images_serial_list = M("addpage_details_images_serial")->field("id,typeid")->where($where)->order("id asc")->select();

				$images_text = array();
				$text_num = $img_num = 0;

				foreach($images_serial_list as $k=>$list){

					$images_text[$k]['typeid'] = $list['typeid'];

					if($list['typeid'] == 1){
						$images_text[$k]['images'] = M("addpage_details_images")->field("image")->where("images_serial_id=".$list['id'])->order("id asc")->select();
						$images_text[$k]['num'] = $img_num;
						$img_num++;
					}else{

						$images_text[$k]['text'] = M("addpage_details_text")->where("images_serial_id=".$list['id'])->order("id asc")->getField("text");
						$images_text[$k]['num'] = $text_num;
						$text_num++;
					}
				}

				//获取按钮设置
				$details_button = M("addpage_details_button")->where("addpage_info_id=".$id)->find();

				//获取商品套餐列表
				$where = array();
				$where['addpage_info_id'] = array("eq",$id);

				//查询套餐列表
				$package_list = M("addpage_package")->where($where)->order("id asc")->select();

				$package_data = array();

				foreach($package_list as $k=>$list){

					$product_list = array();

					$package_data[$k] = $list;

					//查询产品列表
					$package_product = M("addpage_package_product")->where("package_id=".$list['id'])->order("id asc")->select();

					//查询属性列表
					foreach($package_product as $i=>$product){

						$attribute_list = array();

						$product_list[$i]['product_name'] = $product['product_name'];

						//查询属性名称
						$attribute_name = M("addpage_package_attribute_name")->where("product_id=".$product['id'])->order("id asc")->select();

						foreach($attribute_name as $l=>$name){

							$attribute_list[$l] = $name;

							//查询属性值
							$attribute_list[$l]['attribute_val_list'] = M("addpage_package_attribute_val")->where("attribute_name_id=".$name['id'])->order("id asc")->select();

						}

						$product_list[$i]['attribute_name_list'] = $attribute_list;

					}

					$package_data[$k]['product_list'] = $product_list;

				}


				//获取基本信息 - 售后电话
				$where = array();
				$where['id'] = array("eq",$id);
				$where['user_id'] = array("eq",$user_info['user_id']);
				$addpage_info = M("addpage_info")->field("page_name,page_title,as_phone,page_state")->where($where)->find();

				//计算按钮设置显示百份比
				$num = 0;

				if($details_button['button_phone_hide'] == 1){
					$num +=1;
				}

				if($details_button['button_sms_hide'] == 1){
					$num +=1;
				}

				if($details_button['button_buy_hide'] == 1){
					$num +=1;
				}

				if($num > 0){
					$percent = round((100 / $num),3);
				}else{
					$percent = 0;
				}

				//生成属性HTML
				$html = '';

				foreach($package_data as $k=>$data){

					if($k == 0){
						$html .= "<div data-package-detail=\"".$k."\" class=\"attribute_val_".$data['id']." item-group\">";
					}else{
						$html .= "<div data-package-detail=\"".$k."\" class=\"attribute_val_".$data['id']." item-group hide\">";
					}

					foreach($data['product_list'] as $i=>$item){

						$html .= "<p data-product=\"".$k."_0\" data-name=\"".$item['product_name']."\" class=\"title\">".$item['product_name']."</p>";

						foreach($item['attribute_name_list'] as $p=>$name_list){

							$html .= "<p id=\"attribute-name-".$k."_".$i."_".$p."\" class=\"sub-title is-required\" style=\"margin-bottom: 10px;\"> ".$name_list['attribute_name']." <span data-attribute-validate=\"".$k."_".$i."_".$p."\" class=\"ec-validate hide\">请选择".$name_list['attribute_name']."</span> </p>";

							$html .= "<ul class=\"radio-btn-group clear\">";

							foreach($name_list['attribute_val_list'] as $v=>$val){

								$html .= "<li alt=\"".$val['id']."\" data-attribute=\"".$k."_".$i."_".$p."\" data-value=\"".$val['attribute_val']."\" style=\"touch-action: pan-y; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\">".$val['attribute_val']."</li>";

							}

							$html .= "</ul>";

						}

					}

					$html .= "</div>";

				}

				$data_time = time();

				$data = array(
					"id"=>$id,
					"index_images"=>$index_images,
					"details_index"=>$details_index,
					"images_text"=>$images_text,
					"img_num"=>$img_num,
					"text_num"=>$text_num,
					"details_button"=>$details_button,
					"package_data"=>$package_data,
					"addpage_info"=>$addpage_info,
					"html"=>$html,
					"percent"=>$percent,
					"data_time"=>$data_time,
					"ismobile"=>isMobile(),
					"qq"=>$user_info['qq'],
					"code"=>200,
					"msg"=>"OK"
				);

			}else{
				$data = array(
					"code"=>401,
					"msg"=>"访问链接出错!"
				);

			}

		}else{

			$data = array(
				"code"=>400,
				"msg"=>"系统繁忙，请稍后重试!"
			);

		}

		return $data;

	}

	/**
	 * 提交订单
	 */
	public function Ajaxform(){

		$info = I("post.info");

		$order_sn = $this->getrandomstring(2).date("dHis",time()).$info['id'].$info['package_id'].rand(0,9);

		$order_ip = $this->getIPaddress();

		$order_ip_address = $this->taobaoIP($order_ip);

		$product_list = array();

		//获取套餐信息
		$addpage_package = M("addpage_package")->field("package_name")->where("id=".$info['package_id'])->find();

		//查询产品列表
		$package_product = M("addpage_package_product")->where("package_id=".$info['package_id'])->order("id asc")->select();

		//查询属性列表
		foreach($package_product as $i=>$product){

			//查询属性名称
			$attribute_name = M("addpage_package_attribute_name")->where("product_id=".$product['id'])->find();

			if(!empty($attribute_name)){
				//查询属性值
				$attribute_val = M("addpage_package_attribute_val")->where("attribute_name_id=".$attribute_name['id'])->find();
			}

			$arr = array($product['product_name']);

			if(!empty($attribute_name['attribute_name'])){
				$arr = array_merge($arr,array($attribute_name['attribute_name']));
			}
			if(!empty($attribute_name['attribute_val'])){
				$arr = array_merge($arr,array($attribute_val['attribute_val']));
			}

			$product_list[$i] = implode(":",$arr);

		}

		//获取套餐明细
		$package_detailed = $addpage_package['package_name'].":".implode(",",$product_list);

		$items = array(
			"order_sn"=>$order_sn,
			"order_ip"=>$order_ip,
			"order_ip_address"=>$order_ip_address,
			"order_create_time"=>date("Y-m-d H:i:s",time()),
			"order_number"=>$info['package_count'],
			"order_username"=>$info['user_name'],
			"order_phone"=>$info['user_phone'],
			"order_address"=>$info['user_address'],
			"order_state"=>0,
			"order_message"=>$info['user_message'],
			"express_id"=>1,
			"package_detailed"=>$package_detailed,
			"province_id"=>$this->province_city_area($info['user_province']),
			"city_id"=>$this->province_city_area($info['user_city']),
			"county_id"=>$this->province_city_area($info['user_area']),
			"addpage_info_id"=>$info['id'],
			"addpage_package_id"=>$info['package_id']

		);

		$M = M("order");

		//验证TOKEN重复表单提交
		if($M->autoCheckToken($info)){

			$M->startTrans();//开启事务
			$data = array();
			$id = $M->data($items)->add();
			if($id)
			{
				$data['code'] = 200;
				$data['msg'] = "OK";

				//查询订单编号
				$order_sn = M("order")->where("id=".$id)->getField("order_sn");

				//获取商品售后电话
				$as_phone = M("addpage_info")->where("id=".$info['id'])->getField("as_phone");

				//生成商品链接
				$url = "http://".$_SERVER['HTTP_HOST'].U('Home/Mate/index',array('id'=>$info['id']));

				$content = '您的订单已成功提交（'.$addpage_package['package_name'].'，订单编号：'.$order_sn.'），我们会尽快为您安排发货。商品页面：'.$url.' 。如需帮助请联系客服：'.$as_phone.' 【众云电商】';

				//防止短信攻击
				$map['send_phone'] = array('eq',$info['user_phone']);
				$map['send_ip'] =  array('eq',$order_ip);
				$map['_logic'] = 'OR';

				//锁定半小时发送
				$time = time()+10800;
				$send_time = date("Y-m-d H:i:s",$time);
				$map['send_time'] = array('EGT',$send_time);
				$send_sms = M("send_sms")->where($map)->count();

				if($send_sms < 3){

					$sms = send_sms($info['user_phone'],$content);
					//写入日志
					if($sms['code'] == 200){

						$sms_data = array(
							"send_phone"=>$info['user_phone'],
							"send_time"=>date("Y-m-d H:i:s",time()),
							"send_ip"=>$order_ip
						);

						M("send_sms")->data($sms_data)->add();

					}else{
						\Think\Log::record($sms['msg']);
					}
				}

				$M->commit();//提交事务成功
			}else{
				$data['code'] = 400;
				$data['msg'] = "系统繁忙，请稍后重试!";
				$M->rollback();//事务有错回滚
			}

		}else{
			$data['code'] = 401;
			$data['msg'] = "系统繁忙，请稍后重试!";
		}

		return $data;
	}

	/**
	 * 生成订单号随机数
	 */
	public function getrandomstring($len,$chars=null){
		if(is_null($chars)){
			$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		}
		mt_srand(1000*(double)time());
		$str = '';
		for($i = 0,$lc = strlen($chars)-1;$i<$len;$i++){
			$str.= $chars[mt_rand(0,$lc)];
		}
		return $str;
	}

	/**
	 * 获取客户端IP
	 */
	public function getIPaddress(){
		$IPaddress='';
		if (isset($_SERVER)){
			if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
				$IPaddress = $_SERVER["HTTP_X_FORWARDED_FOR"];
			} else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
				$IPaddress = $_SERVER["HTTP_CLIENT_IP"];
			} else {
				$IPaddress = $_SERVER["REMOTE_ADDR"];
			}
		} else {
			if (getenv("HTTP_X_FORWARDED_FOR")){
				$IPaddress = getenv("HTTP_X_FORWARDED_FOR");
			} else if (getenv("HTTP_CLIENT_IP")) {
				$IPaddress = getenv("HTTP_CLIENT_IP");
			} else {
				$IPaddress = getenv("REMOTE_ADDR");
			}
		}
		return $IPaddress;
	}

	/**
	 * 获取客户端IP地址
	 */
	public function taobaoIP($clientIP){
		$taobaoIP = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$clientIP;
		$IPinfo = json_decode(file_get_contents($taobaoIP));
		$province = $IPinfo->data->region;
		$city = $IPinfo->data->city;
		$data = $province.$city;
		return $data;
	}

	/**
	 * 获取省市县数据
	 */
	public function province_city_area($name){

		if(!empty($name)){

			$where['name'] = array('like',"%$name%");

			$city_area = M("province_city_area")->where($where)->find();

			return $city_area['id'];
		}else{

			return '';
		}

	}

}
